<template>
    <div class="question-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <QuestionFilled />
                        </el-icon>
                        <span>问题管理</span>
                        <div class="search-box">
                            <el-input v-model="searchQuery" placeholder="请输入问题内容搜索" clearable @clear="handleSearch"
                                @keyup.enter="handleSearch">
                                <template #suffix>
                                    <el-icon class="search-icon" @click="handleSearch">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                    </div>
                    <div class="header-right">
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <Plus />
                            </el-icon>新增问题
                        </el-button>
                    </div>
                </div>
            </template>

            <el-table :data="questionList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="type" label="类型" width="120">
                    <template #default="{ row }">
                        <el-tag :type="row.type === 'input' ? 'success' : 'primary'">
                            {{ row.type === 'input' ? '输入题' : '选择题' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="content" label="问题内容">
                    <template #default="{ row }">
                        <div class="content-preview">{{ row.content }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="options" label="选项" v-if="showOptionsColumn">
                    <template #default="{ row }">
                        <div v-if="row.type === 'choice'" class="options-preview">
                            {{ formatOptions(row.options) }}
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[8, 10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogType === 'add' ? '新增问题' : '编辑问题'" v-model="dialogVisible" width="600px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="问题类型" prop="type">
                    <el-radio-group v-model="form.type" @change="handleTypeChange">
                        <el-radio label="input">输入题</el-radio>
                        <el-radio label="choice">选择题</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="问题内容" prop="content">
                    <el-input v-model="form.content" type="textarea" :rows="3" placeholder="请输入问题内容" />
                </el-form-item>
                <el-form-item label="选项" prop="options" v-if="form.type === 'choice'">
                    <div class="options-input">
                        <el-tag v-for="(option, index) in optionList" :key="index" closable
                            @close="handleOptionRemove(index)" class="option-tag">
                            {{ option }}
                        </el-tag>
                        <el-input v-if="inputVisible" ref="optionInputRef" v-model="inputValue" class="option-input"
                            size="small" @keyup.enter="handleOptionConfirm" @blur="handleOptionConfirm" />
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">
                            + 添加选项
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuestionFilled, Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const questionList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
    id: null,
    type: 'input',
    content: '',
    options: ''
})

const rules = {
    type: [
        { required: true, message: '请选择问题类型', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入问题内容', trigger: 'blur' }
    ],
    options: [
        { required: true, message: '请输入选项', trigger: 'blur' }
    ]
}

// 是否显示选项列
const showOptionsColumn = computed(() => {
    return questionList.value.some(q => q.type === 'choice')
})

const inputVisible = ref(false)
const inputValue = ref('')
const optionInputRef = ref(null)
const optionList = ref([])

// 获取问题列表
const getQuestionList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/questions/search',
            method: 'get',
            params: {
                pageNum: currentPage.value,
                pageSize: pageSize.value,
                keyword: searchQuery.value
            }
        })
        questionList.value = res.data.records
        total.value = res.data.total
    } catch (error) {
        console.error('获取问题列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 格式化选项显示
const formatOptions = (options) => {
    if (!options) return ''
    try {
        const optionsArray = JSON.parse(options)
        return optionsArray.join('、')
    } catch {
        return options
    }
}

// 新增问题
const handleAdd = () => {
    dialogType.value = 'add'
    form.value = {
        id: null,
        type: 'input',
        content: '',
        options: ''
    }
    optionList.value = []
    dialogVisible.value = true
}

// 编辑问题
const handleEdit = (row) => {
    dialogType.value = 'edit'
    form.value = {
        ...row
    }
    if (row.type === 'choice' && row.options) {
        try {
            optionList.value = JSON.parse(row.options)
        } catch {
            optionList.value = []
        }
    } else {
        optionList.value = []
    }
    dialogVisible.value = true
}

// 删除问题
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该问题吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request({
                url: `/questions/${row.id}`,
                method: 'delete'
            })
            ElMessage.success('删除成功')
            getQuestionList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

// 问题类型改变
const handleTypeChange = (value) => {
    if (value === 'input') {
        form.value.options = ''
        optionList.value = []
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        const submitData = {
            ...form.value,
            options: form.value.type === 'choice'
                ? JSON.stringify(optionList.value)
                : null
        }

        const url = '/questions'
        await request({
            url,
            method: dialogType.value === 'add' ? 'post' : 'put',
            data: submitData
        })

        ElMessage.success(`${dialogType.value === 'add' ? '新增' : '编辑'}成功`)
        dialogVisible.value = false
        getQuestionList()
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitting.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getQuestionList()
}

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val
    getQuestionList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getQuestionList()
}

// 显示输入框
const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        optionInputRef.value?.input?.focus()
    })
}

// 处理选项确认
const handleOptionConfirm = () => {
    if (inputValue.value) {
        optionList.value.push(inputValue.value)
        form.value.options = JSON.stringify(optionList.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

// 处理选项删除
const handleOptionRemove = (index) => {
    optionList.value.splice(index, 1)
    form.value.options = JSON.stringify(optionList.value)
}

onMounted(() => {
    getQuestionList()
})
</script>

<style scoped>
.question-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.search-box {
    width: 250px;
    margin-left: 16px;
}

.search-icon {
    cursor: pointer;
    color: #606266;
}

.search-icon:hover {
    color: #409EFF;
}

.content-preview {
    white-space: pre-wrap;
    word-break: break-all;
}

.options-preview {
    white-space: pre-wrap;
    word-break: break-all;
    color: #606266;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.options-input {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.option-tag {
    margin-right: 8px;
    margin-bottom: 8px;
}

.option-input {
    width: 100px;
    margin-right: 8px;
    vertical-align: bottom;
}

.button-new-tag {
    margin-bottom: 8px;
}
</style>
